<template>
  <div class="app-container">
    <!--    查询对话框-->
    <el-dialog :title="title" v-model="openSearch" :close-on-click-modal="false" draggable width="580px" append-to-body>
      <el-form :model="queryParams" ref="queryForm" v-show="showSearch" label-width="68px">
        <el-form-item label="机台编号" prop="moeJtbh">
          <el-input v-model="queryParams.moeJtbh" placeholder="请输入机台编号" clearable />
        </el-form-item>
        <el-form-item label="综合查询" prop="itmPmgg">
          <el-input v-model="queryParams.itmPmgg" placeholder="请输入客户编码、品名规格" clearable />
        </el-form-item>
        <el-form-item label="营销单" prop="somDjbh">
          <el-input v-model="queryParams.somDjbh" placeholder="请输入营销单号" clearable />
        </el-form-item>
        <el-form-item label="制造单" prop="moeZzdh">
          <el-input v-model="queryParams.moeZzdh" placeholder="请输入制造单号" clearable />
        </el-form-item>
        <el-form-item label="日期" prop="daterange">
          <el-date-picker
            v-model="daterange"
            type="daterange"
            align="right"
            unlink-panels
            range-separator="至"
            start-placeholder="开始日期"
            end-placeholder="结束日期"
            :picker-options="pickerOptions"
            @change="get_info"></el-date-picker>
        </el-form-item>
        <el-form-item label="班次" prop="rpmBcdm">
          <el-radio-group v-model="queryParams.rpmBcdm">
            <el-radio label="白班">白班</el-radio>
            <el-radio label="夜班">夜班</el-radio>
            <el-radio label="所有">所有</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-col :span="24">
          <el-form-item style="margin-top: 25px; display: flex; justify-content: flex-end">
            <el-button type="warning" @click="reset">重置</el-button>
            <el-button @click="cancel">取消</el-button>
            <el-button type="primary" @click="handleQuery">确认</el-button>
          </el-form-item>
        </el-col>
      </el-form>
    </el-dialog>
    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button type="primary" plain icon="el-icon-search" size="mini" @click="handleSearch">搜索</el-button>
      </el-col>
      <Tag type="dot" color="#3399ff">审核</Tag>
      <Tag type="dot" color="#FF44AA">结案待审批</Tag>
      <Tag type="dot" color="#bb0331">结案</Tag>
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="el-icon-download"
          size="mini"
          :loading="exportLoading"
          @click="handleExport"
          v-hasPermi="['marketing:somFinish:export']">
          导出
        </el-button>
      </el-col>
      <!-- <el-col :span="2.2" style="position: absolute; right: 35px; top: 0">
        <Page
          style="margin-right: 0px"
          :current="queryParams.pageNum"
          :page-size="queryParams.pageSize"
          :total="total"
          @on-change="pageChange"
          simple></Page>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar> -->
    </el-row>
    <el-tabs v-model="activeName" @tab-click="handleClick">
      <el-tab-pane label="明细数据" name="first">
        <ux-grid
          ref="plxTableBom"
          widthResize
          :highlightCurrentRow="false"
          :treeConfig="{
            expandAll: true,
            children: 'detailList',
            indent: 5,
          }"
          :default-expand-all="true"
          :edit-config="{
            trigger: 'click',
            mode: 'cell',
            showIcon: !readOnly,
            activeMethod: ({ row }) => {
              return (!row.bomLevel || row.bomLevel == 0) && !readOnly
            },
          }"
          height="600px"
          border
          :cell-style="iCellStyle"
          :data="somList"
          show-summary
          :summary-method="getSummaries"
          :header-cell-style="{ 'text-align': 'center' }">
          <ux-table-column title="机台" show-overflow :show-overflow-tooltip="true" align="center" field="moeJtbh" :tree-node="true" />
          <ux-table-column title="客户编码" :show-overflow-tooltip="true" width="150" align="center" field="itmCustwldm" />
          <ux-table-column title="营销单" :show-overflow-tooltip="true" width="150" align="center" field="somDjbh"></ux-table-column>
          <ux-table-column title="制造单" :show-overflow-tooltip="true" width="150" align="center" field="moeZzdh"></ux-table-column>
          <ux-table-column title="品名规格" :show-overflow-tooltip="true" width="200" align="center" field="itmPmgg" resizable />
          <ux-table-column title="计划数" :show-overflow-tooltip="true" align="center" field="moeScsl"></ux-table-column>
          <ux-table-column title="良品数" :show-overflow-tooltip="true" align="center" field="moeLpsl" />
          <ux-table-column title="入库数" :show-overflow-tooltip="true" align="center" field="moeRksl" />
          <ux-table-column title="调整数" :show-overflow-tooltip="true" align="center" field="moeTzsl" />
          <ux-table-column title="入库差异率" :show-overflow-tooltip="true" align="center" field="warehousingDifferenceRate" />
        </ux-grid>
      </el-tab-pane>
      <el-tab-pane label="按客户编码统计" name="second">
        <ux-grid
          ref="plxTableBom"
          widthResize
          :highlightCurrentRow="false"
          height="600px"
          border
          :cell-style="iCellStyle"
          :data="somList2"
          show-summary
          :summary-method="getSummaries2"
          :header-cell-style="{ 'text-align': 'center' }">
          <ux-table-column title="客户编码" :show-overflow-tooltip="true" align="center" field="itmCustwldm" />
          <ux-table-column title="采集数" :show-overflow-tooltip="true" align="center" field="moeLpsl" />
          <ux-table-column title="入库数" :show-overflow-tooltip="true" align="center" field="moeRksl" />
          <ux-table-column title="不良数" :show-overflow-tooltip="true" align="center" field="blmBlsl" />
          <ux-table-column title="生产不良数" :show-overflow-tooltip="true" align="center" field="rzmBlsl" />
          <ux-table-column title="调整数" :show-overflow-tooltip="true" align="center" field="moeTzsl" />
          <ux-table-column title="机台编号" :show-overflow-tooltip="true" align="center" field="jtmJtbh" />
        </ux-grid>
      </el-tab-pane>
    </el-tabs>
  </div>
</template>

<script>
import { handleQueryList, handleQueryList2, warehousingDifferenceReportExport, sum1, sum2 } from '@/api/repertory/WarehousingDifferenceReport'

import { getAllCustomer } from '@/api/project/customer'

export default {
  name: 'WarehousingDifferenceReport',
  data() {
    return {
      // 遮罩层
      loading: true,
      activeName: 'first',
      tableH: document.body.clientHeight - 230,
      // 导出遮罩层
      exportLoading: false,
      // 选中数组
      ids: [],
      readOnly: false,

      somDjbhs: [],
      currentData: [],
      //标题1
      title: '',
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 营销订单维护表格数据
      somList: [],
      somList2: [],
      // 是否显示弹出层
      open: false,
      openSearch: false,
      check_finish: false,
      finish_reason: '正常结案流程',
      // 状态标志字典
      somZtbzOptions: [],
      //根据客户代码查询出物料信息
      selectedItmMstr: [],
      // 订单类型字典
      somTypeOptions: [],
      itCarOptions: [],
      somAllTypeOptions: [],
      //客户类型
      customerOptions: [],
      // 日期范围
      daterange: [],
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: document.body.clientHeight > 900 ? 25 : 18,
        somTypeList: [],
        somZtbzList: [],
        rpmBcdm: null,
      },
      // 表单参数
      form: {},
      sumList: {},
      sumList2: {},
      //日期初始化
      pickerOptions: {
        shortcuts: [
          {
            text: '最近一周',
            onClick(picker) {
              const end = new Date()
              const start = new Date()
              start.setTime(start.getTime() - 3600 * 1000 * 24 * 7)
              picker.$emit('pick', [start, end])
            },
          },
          {
            text: '最近一个月',
            onClick(picker) {
              const end = new Date()
              const start = new Date()
              start.setTime(start.getTime() - 3600 * 1000 * 24 * 30)
              picker.$emit('pick', [start, end])
            },
          },
          {
            text: '最近三个月',
            onClick(picker) {
              const end = new Date()
              const start = new Date()
              start.setTime(start.getTime() - 3600 * 1000 * 24 * 90)
              picker.$emit('pick', [start, end])
            },
          },
        ],
      },
    }
  },
  created() {
    this.getList()
    this.getDicts('sys_order_ztbz').then((response) => {
      for (let i of response.data) {
        if (i.dictValue === '2') {
          i.dictLabel = '审核'
        }
      }
      this.somZtbzOptions = response.data
      this.somZtbzOptions.push({ dictValue: '', dictLabel: '全部' })
      this.somZtbzOptions = this.somZtbzOptions.filter((item) => item.dictValue !== '1')
    })
    this.getDicts('sys_order_style').then((response) => {
      this.somTypeOptions = response.data
    })
    this.getAllDicts('sys_order_style').then((response) => {
      this.somAllTypeOptions = response.data
    })
  },
  methods: {
    iCellStyle({ row, column, rowIndex, columnIndex }) {
      // 通过状态
      if (row.somZtbz == '2') {
        return 'color:#3399ff'
      }
      // 结案申请状态
      else if (row.somZtbz == '3') {
        return 'color:#FF44AA'
      }
      // 结案状态
      else if (row.somZtbz == '4') {
        return 'color:#bb0331'
      }
    },
    /** 查询营销订单维护列表 */
    getList() {
      this.loading = true
      handleQueryList(this.queryParams).then((response) => {
        this.somList = response.data
        this.loading = false
      })

      sum1(this.queryParams).then((response) => {
        this.sumList = response.data
      })
    },
    getList2() {
      this.loading = true
      handleQueryList2(this.queryParams).then((response) => {
        this.somList2 = response.data
        this.loading = false
      })

      sum2(this.queryParams).then((response) => {
        this.sumList2 = response.data
      })
    },
    handleExport() {
      const queryParams = this.queryParams
      this.$confirm('是否确认导出所有入库差异数据项?', '警告', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
      })
        .then(() => {
          this.exportLoading = true
          return warehousingDifferenceReportExport(queryParams)
        })
        .then((response) => {
          this.download(response.msg)
          this.exportLoading = false
        })
        .catch(() => {})
    },
    // 取消按钮
    cancel() {
      this.open = false
      // this.reset()
      this.openSearch = false
    },
    // 表单重置
    reset() {
      this.daterange = []
      this.resetForm('queryForm')
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1
      if (this.activeName == 'first') {
        this.getList()
      } else {
        this.getList2()
      }
      this.openSearch = false
    },
    /** 重置按钮操作 */
    resetQuery() {
      // this.resetForm('queryForm')
      this.handleQuery()
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map((item) => item.somId)
      this.somDjbhs = selection.map((item) => item.somDjbh)
      this.currentData = selection
      this.single = selection.length !== 1
      this.multiple = !selection.length
    },
    handleSearch() {
      // this.reset()
      this.title = '查询'
      this.openSearch = true
    },
    clickRow(row) {
      this.$refs.somCheckTable.toggleRowSelection(row)
    },
    pageChange(page) {
      this.queryParams.pageNum = page
      this.getList()
    },
    get_info() {
      if (this.daterange == null) {
        this.queryParams.beginTime = null
        this.queryParams.endTime = null
      } else {
        this.queryParams.beginTime = this.$moment(this.daterange[0]).format('YYYY-MM-DD')
        this.queryParams.endTime = this.$moment(this.daterange[1]).format('YYYY-MM-DD')
      }
    },
    getSummaries(param) {
      const { columns, data } = param
      const sums = []
      columns.forEach((column, index) => {
        if (index === 0) {
          sums[index] = '本页合计:'
          return
        }
        if (!['somDdsl', 'moeLpsl', 'moeRksl', 'somChsl', 'somWchl'].includes(column.property) || !column.property) {
          sums[index] = ' '
          return
        }

        const values = data.map((item) => Number(item[column.property]))
        if (!values.every((value) => isNaN(value))) {
          sums[index] = values.reduce((prev, curr) => {
            const value = Number(curr)
            if (!isNaN(value)) {
              return prev + curr
            } else {
              return prev
            }
          }, 0)
        } else {
          sums[index] = 'N/A'
        }
      })

      return [
        [
          '总计:',
          '',
          '',
          '',
          '',
          this.sumList.moeScsl,
          this.sumList.moeLpsl,
          this.sumList.moeRksl,
          this.sumList.moeTzsl,
          this.sumList.warehousingDifferenceRate,
        ],
      ]
    },
    getSummaries2(param) {
      const { columns, data } = param
      const sums = []
      columns.forEach((column, index) => {
        if (index === 0) {
          sums[index] = '本页合计:'
          return
        }
        if (!['moeLpsl', 'blmBlsl', 'moeRksl', 'moeTzsl', 'rzmBlsl'].includes(column.property) || !column.property) {
          sums[index] = ' '
          return
        }

        const values = data.map((item) => Number(item[column.property]))
        if (!values.every((value) => isNaN(value))) {
          sums[index] = values.reduce((prev, curr) => {
            const value = Number(curr)
            if (!isNaN(value)) {
              return prev + curr
            } else {
              return prev
            }
          }, 0)
        } else {
          sums[index] = 'N/A'
        }
      })

      return [['总计:', this.sumList2.moeLpsl, this.sumList2.moeRksl, this.sumList2.blmBlsl, this.sumList2.rzmBlsl, this.sumList2.moeTzsl, '']]
    },
    handleClick(tab) {
      if (tab.name == 'first') {
        this.getList()
      } else {
        this.getList2()
      }
    },
  },
}
</script>

<style lang="scss" scoped></style>
